<template>
  <div>
    <div>
      <el-card style="text-align:center;height:10vh;border-radius:5px">
        <el-autocomplete
          v-model="formData.key"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入内容"
          @select="handleSelect"
          class="openSearch"
          clearable
        >
          <el-button
            @click="submitFormData"
            slot="append"
            icon="el-icon-search"
            style="background-color: #25aae2"
          ></el-button>
        </el-autocomplete>
      </el-card>
      <el-card style="background-color: #f3f3f3">
        <b style="float:left;margin-top:10px">筛选：</b>
        <div>
          <el-select
            v-model="formData.fileSize"
            slot="prepend"
            placeholder="文件大小"
            @change="changeList1($event)"
          >
            <el-option label="不限大小" value="0"></el-option>
            <el-option label="0KB-50KB" value="1"></el-option>
            <el-option label="50KB-100KB" value="2"></el-option>
            <el-option label="100KB-500KB" value="3"></el-option>
            <el-option label="500KB-1MB" value="4"></el-option>
            <el-option label="1MB-10MB" value="5"></el-option>
            <el-option label="10MB-50MB" value="6"></el-option>
            <el-option label="50MB以上" value="7"></el-option>
          </el-select>
          <el-select
            v-model="formData.fileType"
            slot="prepend"
            placeholder="文件类型"
            @change="changeList2($event)"
          >
            <el-option label="不限类型" value="0"></el-option>
            <el-option label="doc" value="1"></el-option>
            <el-option label="docx" value="2"></el-option>
            <el-option label="pdf" value="3"></el-option>
            <el-option label="png" value="4"></el-option>
            <el-option label="jpg" value="5"></el-option>
            <el-option label="txt" value="6"></el-option>
            <el-option label="xls" value="7"></el-option>
            <el-option label="xlsx" value="8"></el-option>
            <el-option label="ppt" value="9"></el-option>
            <el-option label="pptx" value="10"></el-option>
            <el-option label="md" value="11"></el-option>
            <el-option label="zip" value="12"></el-option>
            <el-option label="rar" value="13"></el-option>
            <el-option label="mp4" value="14"></el-option>
            <el-option label="mp3" value="15"></el-option>
            <el-option label="html" value="16"></el-option>
          </el-select>
          <el-select
            v-model="formData.fileJoint"
            slot="prepend"
            placeholder="文件范围"
            @change="changeList3($event)"
          >
            <el-option label="不限范围" value="0"></el-option>
            <el-option label="仅限标题" value="1"></el-option>
            <el-option label="仅限作者" value="2"></el-option>
            <el-option label="仅限内容" value="3"></el-option>
            <el-option label="标题和作者" value="4"></el-option>
            <el-option label="标题和内容" value="5"></el-option>
            <el-option label="作者和内容" value="6"></el-option>
          </el-select>
          <el-select
            v-model="formData.fileDate"
            slot="prepend"
            placeholder="文件日期"
            @change="changeList4($event)"
          >
            <el-option label="不限日期" value="0"></el-option>
            <el-option label="1天内" value="1"></el-option>
            <el-option label="2天内" value="2"></el-option>
            <el-option label="4天内" value="3"></el-option>
            <el-option label="1周内" value="4"></el-option>
            <el-option label="2周内" value="5"></el-option>
            <el-option label="1月内" value="6"></el-option>
            <el-option label="3月内" value="7"></el-option>
            <el-option label="6月内" value="8"></el-option>
            <el-option label="1年内" value="9"></el-option>
          </el-select>
          <el-dropdown
            @command="handleCommand"
            style="float:right;margin-top:10px"
          >
            <span class="el-dropdown-link">
              综合排序<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="a">标题优先</el-dropdown-item>
              <el-dropdown-item command="b">作者优先</el-dropdown-item>
              <el-dropdown-item command="c">内容优先</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-card>
      <div class="block" style="text-align: center;">
        <el-card class="mycard" style="height: auto">
          <el-row>
            <!-- 表格展示 -->
            <el-table
              :data="tableData"
              style="width: 100%"
              ref="multipleTable"
              highlight-current-row
              @selection-change="handleSelectionChange"
              @current-change="handleCurrentChange"
              :default-sort="{ prop: 'id', order: 'descending' }"
            >
              <el-table-column type="selection" width="55"></el-table-column>

              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-form label-position="left" inline class="demo-table-expand">
                    <el-form-item label="文件名称">
                      <span v-html='props.row.name'></span>
                    </el-form-item>
                    <el-form-item label="文件类型">
                      <span>{{ props.row.type }}</span>
                    </el-form-item>
                    <el-form-item label="文件大小">
                      <span>{{ props.row.size + " KB"}}</span>
                    </el-form-item>
                    <el-form-item label="文件上传者">
                      <span v-html='props.row.owner'></span>
                    </el-form-item>
                    <el-form-item label="文件上传时间">
                      <span>{{ props.row.uploadDate }}</span>
                    </el-form-item>
                    <el-form-item label="文件部分内容">
                      <span v-html='props.row.content'></span>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>

              <el-table-column prop="name" label="名称" sortable>
                <template slot-scope="scope" class="rowText">
                  <i></i>
                  <div class="icon">
                    <svg class="icons" aria-hidden="true">
                      <use v-bind:xlink:href="scope.row.icon"></use>
                    </svg>
                  </div>
                  <div class="text">
                    <p v-html='scope.row.name' class="rowname"  @click="preview(scope.row)" style="margin-left:5px"></p>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="owner"
                label="上传者"
                sortable
                width="200">
                <template slot-scope="scope">
                  <p v-html='scope.row.owner'></p>
                </template>
              </el-table-column>
              <el-table-column
                prop="uploadDate"
                label="修改时间"
                sortable
                width="280"
              ></el-table-column>
              <el-table-column
                prop="type"
                label="类型"
                sortable
                width="180"
              ></el-table-column>
              <el-table-column
                prop="size"
                label="大小"
                sortable
                width="220"
              ></el-table-column>
              <!-- 操作按钮 -->
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    @click="handleEdit(scope.$index, scope.row)"
                    icon="el-icon-edit"
                    circle
                    plain
                  ></el-button>
                  <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    @click.native.prevent="deleteRow(scope.$index, scope.row)"
                    circle
                  ></el-button>
                  <el-button
                    type="success"
                    plain
                    icon="el-icon-share"
                    circle
                    @click="getShareLink(scope.$index, scope.row)"
                  ></el-button>
                  <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    @click="download(scope.row)"
                    circle
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
            <br />
            <!-- 分页 -->
            <el-pagination
              style="margin-top: auto"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="formData.currentPage"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </el-row>
        </el-card>
        <!-- 编辑 -->
        <el-dialog
            title="文件重命名"
            :visible.sync="editFormVisible"
            :close-on-click-modal="false"
            class="edit-form"
            center
        >
          <el-form :model="editForm" label-width="80px" ref="editForm">
            <el-form-item label="名称" prop="Name">
              <el-input v-model="editForm.name" auto-complete="off"></el-input>
              <el-input
                  v-model="editForm.date"
                  auto-complete="off"
                  :disabled="true"
              ></el-input>
              <el-input
                  v-model="editForm.storage"
                  auto-complete="off"
                  :disabled="true"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click.native="editFormVisible = false">取 消 </el-button>
            <el-button type="primary" @click.native="handleUpdate('editForm')"
            >确 定
            </el-button>
          </div>
        </el-dialog>
        <!-- 外链设置 -->
        <el-dialog title="文件分享" :visible.sync="dialogShareFormVisible" center>
          <el-form :model="form" ref="form">
            <el-form-item
                label="链接有效期至："
                :rules="{
            required: true,
          }"
            >
              <el-col :span="11" class="timeCol">
                <el-date-picker
                    v-model="shareDate"
                    type="date"
                    placeholder="选择日期"
                    :picker-options="pickerOptions"
                >
                </el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="是否设置提取码：">
              <el-radio v-model="radio" label="1">是</el-radio>
              <el-radio v-model="radio" label="2">否</el-radio>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="createShareLink" round plain
            >生成链接</el-button
            >
          </div>
          <div slot="footer">
            <small>tips: 若分享的文件是视频或音频,有效期仅为一小时</small>
          </div>
        </el-dialog>
        <!-- 外链生成 -->
        <el-dialog
            title="分享链接"
            :visible.sync="shareLinkDialog"
            center
            :close-on-click-modal="false"
            @opened="ShowQRCode()"
        ><img
            src="@/assets/css/images/fileShare.svg"
            @click="goShare"
            class="shareButton"
            alt=""
        />
          <el-form :model="form" ref="form">
            <el-form-item label="分享链接：" :label-width="formLabelWidth">
              <el-input v-model="form"> </el-input>
            </el-form-item>
            <el-form-item
                label="提取码："
                :rules="[{ type: 'number', message: '提取码必须为数字值' }]"
            >
              <el-input type="textarea" v-model="code"></el-input>
            </el-form-item>
            <el-form-item label="外链二维码:"> </el-form-item>
          </el-form>
          <div id="qrcode" style="margin-left:42%"></div>
          <!-- tips -->
          <div slot="footer">
            <small>tips: 有效期至截止日期当天23:59:59</small>
          </div>
        </el-dialog>
        <el-dialog :visible.sync="videoDialog" style="">
          <video
              :src="videoSrc"
              controls="controls"
              width="100%"
              height="100%"
              style="border-radius:10px"
          ></video>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";

const axios = require("axios");
export default {
  data() {
    return {
      optionsMatching: [],
      options: {
        value: "",
        id: 1
      },
      total: 3,
      code: "",
      //定义属性
      name: undefined,
      date: undefined,
      storage: undefined,
      editFormVisible: false,
      //生成分享链接
      dialogShareFormVisible: false,
      uploadDialog: false,
      panelShow: false,
      uploadDlg: false,
      //分享链接
      shareLinkDialog: false,
      editForm: {
        id: "",
        name: ""
      },
      //有效期
      shareDate: "",
      formData: {
        key: "",
        fileSize: "",
        fileType: "",
        fileJoint: "",
        fileDate: "",
        priority: "",
        currentPage: 1,
      },
      confirmForm: {
        shareDate: "",
        code: "",
        url: "",
      },
      videoSrc: "",
      videoDialog: false,
      radio: "2",
      //时间选择器配置
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
        shortcuts: [
          {
            text: "当天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "1天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "7天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
          {
            text: "14天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 14);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      //表格数据
      tableData: [],
    };
  },
  methods: {
    getlist(){
      let params = this.formData;
      let url = "http://49.234.13.136:9090/queryResult"; //通常本地开发会遇到跨域问题，所以我们需要在config的index.js里面配置proxyTable反向代理，具体详情自行百度，有很多很清楚的讲解与写法。
      // **1.post请求，res即为请求成功后后端返回的信息。**
      console.log(params);
      this.$http
          .post(url, params)
          .then((res) => {
            this.tableData = res.data.data.files;
            this.total = res.data.data.recordCount;
            console.log("请求成功");
            console.log(res);
            console.log(this.tableData);
          })
          .catch((error) => {
            console.log("请求失败");
            console.log(error);
          });
    },
    handleEdit: function(index, row) {
      this.editFormVisible = true; //dialog对话窗口打开
      this.editForm = Object.assign({}, row); //将数据传入dialog页面
      this.editForm.index = index; //传递当前index
    },
    handleUpdate(formName) {
      console.log(this.editForm.id, this.editForm.oldname);
      this.$http
          .post(`http://49.234.13.136:9090/pubfiles/updatefilename/${this.editForm.id}/${this.editForm.name}`)
          .then((res) => {
            this.$message.success("重命名成功！");
            this.editFormVisible = false;
          });
    },
    preview(row) {
      console.log(row.url);
      window.open(
          row.url
      );
    },
    // 文件删除
    async deleteRow(index, row) {
      const confirmResult = await this.$confirm("此操作将永久删除该文件，是否继续？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => {
        return err;
      });
      if (confirmResult !== 'confirm') {
        return this.$message.info("已经取消删除")
      }
      console.log(row.id);
      const {data: res} = await this.$http.delete(`http://49.234.13.136:9090/pubfiles/delete/${row.id}`).then(res => {
        console.log(res);
        if (res.data.code != '200') {
          this.$message.error("删除失败")
        } else {
          this.$message.success("删除成功");
          this.tableData.splice(index,1);
          this.total--;
        }
      });
      this.getlist()
    },
    // 加载二维码
    ShowQRCode() {
      document.getElementById("qrcode").innerHTML = "";
      // this.qrcode = this.$QRCode();
      let qrcode = new QRCode("qrcode", {
        width: 132,
        height: 132,
        text: this.shareURL, // 二维码地址
      });
    },
    //文件下载
    download(item) {
      console.log("item:",item);
      this.$http({
        method: 'get',
        url: `http://49.234.13.136:9090/pubfiles/download/${item.id}`,
        responseType: "blob",
      }).then((res) => {
        let blob = new Blob([res.data]);
        console.log(res);
        let downloadElement = document.createElement("a");
        console.log("downloadElement", downloadElement);
        let href = window.URL.createObjectURL(blob); //创建下载的链接
        console.log("href", href);
        downloadElement.href = href;
        downloadElement.style.display = 'none'
        downloadElement.download = item.name + '.' + item.type; //下载后文件名
        document.body.appendChild(downloadElement);
        console.log("downloadElement", downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      });
    },
    createShareLink() {
      if (this.shareDate !== "") {
        this.dialogShareFormVisible = false;
        setTimeout(() => {
          this.shareLinkDialog = true;
          this.$message.success("链接生成成功,有效期至" + this.shareDate);
        }, 500);
      } else {
        this.$message.error("请设置外链有效期！");
      }
      //随机生成提取码
      if (this.radio == 1) {
        var code = "";
        for (var i = 0; i < 6; i++) {
          var radom = Math.floor(Math.random() * 10);
          code += radom;
        }
        this.code = code;
      } else {
        this.code = "";
      }
      this.confirmForm.url = this.shareURL;
      this.confirmForm.shareDate = this.shareDate;
      this.confirmForm.code = code;
      this.$http.post(`${this.systemURL}/userFile/shareLink`, this.confirmForm);
    },
    getShareLink: function(index, row) {
      this.dialogShareFormVisible = true; //dialog对话窗口打开
      var url = Object.assign({}, row);
      // console.log(row);
      // 传文件id获取文件URL
      this.$http
          .post(`${this.systemURL}/userFile/filePreview`, row)
          .then((res) => {
            this.shareURL = res.data.data;
          });
    },
    goShare() {
      var { href } = this.$router.resolve({
        name: "sharePage",
      });
      console.log(this.confirmForm.url);
      localStorage.setItem("url", this.confirmForm.url);
      localStorage.setItem("code", this.code);
      localStorage.setItem("time", this.shareDate.getTime());
      window.open(href);
    },
    submitFormData() {
      if (!this.formData.key) {
        this.$message({
          message: "请输入需要查询的语句！",
          type: "warning",
        });
        return;
      }
      /**
       * url  url地址
       * params请求数据即需要传递的参数
       */
      console.log(this.formData);
      if (!this.formData.fileSize) this.formData.fileSize = "0";
      if (!this.formData.fileJoint) this.formData.fileJoint = "0";
      if (!this.formData.fileType) this.formData.fileType = "0";
      if (!this.formData.fileDate) this.formData.fileDate = "0";
      let params = this.formData;
      let url = "http://49.234.13.136:9090/queryResult"; //通常本地开发会遇到跨域问题，所以我们需要在config的index.js里面配置proxyTable反向代理，具体详情自行百度，有很多很清楚的讲解与写法。
      // **1.post请求，res即为请求成功后后端返回的信息。**
      console.log(params);
      this.$http
        .post(url, params)
        .then((res) => {
          this.tableData = res.data.data.files;
          this.total = res.data.data.recordCount;
          this.formData.currentPage = 1
          console.log("请求成功");
          console.log(res);
          console.log(this.tableData);
        })
        .catch((error) => {
          console.log("请求失败");
          console.log(error);
        });
    },
    changeList1(id) {
      let obj = {};
      obj = this.model.find((item) => {
        //model就是上面的数据源
        return item.value === id; //筛选出匹配数据
      });
      this.formData.fileSize = obj.model.id;
    },
    changeList2(id) {
      let obj = {};
      obj = this.model.find((item) => {
        //model就是上面的数据源
        return item.value === id; //筛选出匹配数据
      });
      this.formData.fileType = obj.model.id;
    },
    changeList3(id) {
      let obj = {};
      obj = this.model.find((item) => {
        //model就是上面的数据源
        return item.value === id; //筛选出匹配数据
      });
      this.formData.fileJoint = obj.model.id;
    },
    changeList4(id) {
      let obj = {};
      obj = this.model.find((item) => {
        //model就是上面的数据源
        return item.value === id; //筛选出匹配数据
      });
      this.formData.fileDate = obj.model.id;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.formData.currentPage = val;
      if (!this.formData.fileSize) this.formData.fileSize = "0";
      if (!this.formData.fileJoint) this.formData.fileJoint = "0";
      if (!this.formData.fileType) this.formData.fileType = "0";
      if (!this.formData.fileDate) this.formData.fileDate = "0";
      let params = this.formData;
      let url = "http://49.234.13.136:9090/queryResult"; //通常本地开发会遇到跨域问题，所以我们需要在config的index.js里面配置proxyTable反向代理，具体详情自行百度，有很多很清楚的讲解与写法。
      // **1.post请求，res即为请求成功后后端返回的信息。**
      console.log(params);
      this.$http
        .post(url, params)
        .then((res) => {
          this.tableData = res.data.data.files;
          console.log("请求成功");
          console.log(res);
          console.log(this.tableData);
        })
        .catch((error) => {
          console.log("请求失败");
          console.log(error);
        });
      console.log(`当前页: ${val}`);
    },
    //综合排序，相关度排序
    handleCommand(command) {
      if(command==="a"&&(this.formData.fileJoint==='2'||this.formData.fileJoint==='3'||this.formData.fileJoint==='6'))this.$message("标题范围未包含”标题”，排序无效");
      else if(command==="b"&&(this.formData.fileJoint==='1'||this.formData.fileJoint==='3'||this.formData.fileJoint==='5'))this.$message("标题范围未包含”作者”，排序无效");
      else if(command==="c"&&(this.formData.fileJoint==='1'||this.formData.fileJoint==='2'||this.formData.fileJoint==='4'))this.$message("标题范围未包含”内容”，排序无效");
      else {
        if (!this.formData.fileSize) this.formData.fileSize = "0";
        if (!this.formData.fileJoint) this.formData.fileJoint = "0";
        if (!this.formData.fileType) this.formData.fileType = "0";
        if (!this.formData.fileDate) this.formData.fileDate = "0";
        this.formData.priority = command
        let params = this.formData;
        let url = "http://49.234.13.136:9090/queryResult"; //通常本地开发会遇到跨域问题，所以我们需要在config的index.js里面配置proxyTable反向代理，具体详情自行百度，有很多很清楚的讲解与写法。
        // **1.post请求，res即为请求成功后后端返回的信息。**
        console.log(params);
        this.$http
            .post(url, params)
            .then((res) => {
              this.tableData = res.data.data.files;
              this.total = res.data.data.recordCount;
              this.formData.currentPage = 1
              console.log("请求成功");
              console.log(res);
              console.log(this.tableData);
              this.$message("排序成功！");
            })
            .catch((error) => {
              console.log("请求失败");
              console.log(error);
              this.$message("排序失败！");
            });
      }
    },
    querySearchAsync(queryString, cb) {
      let results = []
      let url = "http://49.234.13.136:9090/queryMatch"
      this.options.value = queryString
      let params = this.options
      this.$http
          .post(url, params)
          .then((res) => {
            console.log("请求成功");
            results = res.data.data
            console.log(this.optionsMatching);
            cb(results)
          })
          .catch((error) => {
            console.log("请求失败");
            console.log(error);
          });
    },
    handleSelect(item) {
      this.formData.key = item.value
      console.log(item);
    },
    loadAll() {
      return this.optionsMatching;
    },
  },
  mounted() {
    this.optionsMatching = this.loadAll();
  },
};
</script>

<style lang="less" scoped>
.openSearch {
  width: 50% !important;
  border-radius: 5px;
  box-shadow: 0 0 15px #c9d1d4;
}
.el-select {
  width: 130px;
}
.fileimg {
  width: 35px;
  height: 32px;
}
.shareButton {
  width: 20px;
  height: 30px;
  margin-left: 95%;
  margin-bottom: -20px;
  cursor: pointer;
  z-index: 999;
}
.rowText {
  display: table-cell;
  text-align: center;
}
.icon,
.text {
  display: table-cell;
  vertical-align: middle;
  margin-right: 5px;
}
.opbutton {
  display: table-cell;
  vertical-align: middle;
  margin-right: 15px !important;
}
.share {
  opacity: 1;
  display: table-cell;
  vertical-align: middle;
  > .shareimg {
    width: 25px;
    height: 30px;
  }
}
.svg {
  width: 100px;
}
.dialog-footer {
  margin-bottom: 20px;
  margin-top: -40px;
}
.rowname {
  cursor: pointer;
}
.batchDelete {
  opacity: 0;
}
.batchDelete1 {
  opacity: 1;
}
.timeCol {
  width: 230px;
}
.line {
  width: 5px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
// 加个通用样式把，不然引入贼大。
.icons {
  width: 35px;
  height: 32px;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
</style>
